package com.linewow.xhyy.nihaonew.activity.location;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.linewow.xhyy.nihaonew.R;
import com.linewow.xhyy.nihaonew.adapter.CountryAdapter;
import com.linewow.xhyy.nihaonew.base.BaseActivity;
import com.linewow.xhyy.nihaonew.entity.NiHaoGeneral;
import com.linewow.xhyy.nihaonew.entity.country.CountryInfo;
import com.linewow.xhyy.nihaonew.entity.user.UserInfoChange;
import com.linewow.xhyy.nihaonew.model.AppConstants;
import com.linewow.xhyy.nihaonew.net.api.NiHaoOkgo;
import com.linewow.xhyy.nihaonew.other.country.CharacterParserUtil;
import com.linewow.xhyy.nihaonew.other.country.CountryComparator;
import com.linewow.xhyy.nihaonew.other.country.GetCountryNameSort;
import com.linewow.xhyy.nihaonew.util.CommonUtil;

import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by LXR on 2016/10/20.
 */
public class LocationCountryActivity extends BaseActivity {
    @Bind(R.id.toolbar_find_title)
    TextView toolbarFindTitle;
    @Bind(R.id.toolbar_find_left)
    ImageView toolbarFindLeft;
    @Bind(R.id.toolbar_find_right)
    ImageView toolbarFindRight;
    @Bind(R.id.toolbar_find_right_tv)
    TextView toolbarFindRightTv;
    @Bind(R.id.toolbar_find_toolbar)
    Toolbar toolbarFindToolbar;
    @Bind(R.id.location_country_lv)
    ListView locationCountryLv;
    private Gson gson;
    private String TAG = "LocationCountryActivity";
    private Type countryInfoType;
    private TextView nowTv;

    private CharacterParserUtil util;
    private GetCountryNameSort sortUtil;
    private CountryComparator countryComparator;
    private CountryAdapter adapter;

    private List<CountryInfo>list;
    private boolean ChineseFlag;
    @Override
    public void initView() {
        super.initView();
        setContentView(R.layout.activity_location_country);
        ButterKnife.bind(this);
        toolbarFindRight.setVisibility(View.GONE);
        toolbarFindRightTv.setVisibility(View.GONE);
        toolbarFindLeft.setImageResource(R.mipmap.icon_back_white);
        toolbarFindTitle.setText(getResources().getString(R.string.title_location));

        View view1 = View.inflate(LocationCountryActivity.this, R.layout.view_country_head_now, null);
        nowTv = (TextView) view1.findViewById(R.id.country_head_now_tv);
        locationCountryLv.addHeaderView(view1);

        View view = View.inflate(LocationCountryActivity.this, R.layout.view_country_head, null);
        locationCountryLv.addHeaderView(view);


        locationCountryLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(position==1){
                    Intent intent=new Intent(LocationCountryActivity.this,LocationProvinceActivity.class);
                    startActivityForResult(intent,9);
                }else if(position>1){

                    CountryInfo info=list.get(position-2);
                    if(info.abbreviation.equals("China")){
                        Intent intent=new Intent(LocationCountryActivity.this,LocationProvinceActivity.class);
                        startActivityForResult(intent,9);
                    }else{
                        nowTv.setText(info.countryName);
                        requestInfo(info.abbreviation);
                    }


                }
            }
        });
    }

    private void requestInfo(String abbreviation) {
        showLoading();
        NiHaoOkgo.setProfileInfo("area",abbreviation)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<NiHaoGeneral<String>>() {
                    @Override
                    public void call(NiHaoGeneral<String> stringNiHaoGeneral) {
                        if(stringNiHaoGeneral.status){
                            dismissLoading();
                            setResult(AppConstants.CONFIGURECOUNTRYCODE);
                            finish();
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        Log.e(TAG, "错误信息" + throwable.getMessage());
                        showToast(getString(R.string.message_no_internet));
                        finish();
                    }
                });
    }
    @Override
    public void initData() {
        super.initData();
        Bundle bundle=getIntent().getExtras();
        if(bundle!=null){
            UserInfoChange userInfoChange=bundle.getParcelable("info");
            if(userInfoChange!=null){
                nowTv.setText(userInfoChange.location);
            }
        }
        ChineseFlag=CommonUtil.ChineseLocale(LocationCountryActivity.this);
        Log.e(TAG,"是否是chinalog"+ChineseFlag);
        initGson();
        util = new CharacterParserUtil();
        sortUtil = new GetCountryNameSort();
        countryComparator = new CountryComparator();
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String json = CommonUtil.getJson(LocationCountryActivity.this, AppConstants.COUNTRYJSON);
                subscriber.onNext(json);
                subscriber.onCompleted();
            }
        })
                .map(new Func1<String, List<CountryInfo>>() {
                    @Override
                    public List<CountryInfo> call(String s) {
                        List<CountryInfo> list = gson.fromJson(s, countryInfoType);
                        for (CountryInfo info : list) {
                            String spellKsy = util.getSelling(ChineseFlag?info.countryName:info.abbreviation);
                            String index = sortUtil.getSortLetterBySortKey(spellKsy);
                            info.setIndex(index);//设置了新的index
                        }
                        Collections.sort(list, countryComparator);
                        return list;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<CountryInfo>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(List<CountryInfo> countryInfos) {
                        list=countryInfos;
                        adapter = new CountryAdapter(LocationCountryActivity.this,list);
                        locationCountryLv.setAdapter(adapter);


                    }
                });
    }

    private void initGson() {
        gson=new Gson();
        countryInfoType = new TypeToken<List<CountryInfo>>() {
        }.getType();
    }

    @Override
    public void initList() {
        super.initList();
    }


    @OnClick({R.id.toolbar_find_left})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_find_left:
                finish();
                break;

        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==9&&resultCode==RESULT_OK){
            Log.e(TAG,"接受到了回调了");
            Bundle bundle=data.getExtras();
            CountryInfo info=bundle.getParcelable("info");
            requestInfo(info.abbreviation);
        }
    }
}
